﻿using System;
using msilgc.cbuilder.CSyntaxTree;
using msilgc.cbuilder.MSILSyntaxTree;
using msilgc.CSyntaxTree;

namespace msilgc.cbuilder.CBuilder {
    internal class LoadObjectTranslator : ITranslator {
        private readonly VariableFactory _varFactory;

        public LoadObjectTranslator(VariableFactory varFactory) {
            _varFactory = varFactory;
        }

        public ICStatement TranslateAndAdd(CMethodBody methodBody, CBasicBlock currentBlock, BasicBlock block, Instruction instruction) {
            IVariable sourcePtr = EvaluationStackHelper.PopVariableOffEvaluationStack(currentBlock);
            if(!sourcePtr.IsPointer)
            {
                throw new Exception("expected source to be a pointer: " + sourcePtr.ToString());
            }
            IVariable target = _varFactory.CreateNext(sourcePtr.Type);
            AssignToLocalVariable assignStm = new AssignToLocalVariable(sourcePtr, target){DereferenceSourcePointer = true};
            currentBlock.Statements.Add(assignStm);
            return assignStm;
        }
    }
}
